package com.universal_library.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.universal_library.AppConfig;
import com.universal_library.utils.ImageLoader;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by solin on 2017/11/22.
 */

public abstract class BaseAdapter<T, VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {
    protected LayoutInflater mInflater;
    protected Context mContext;
    private RequestManager mImageLoder;
    public List<T> mItems = new ArrayList<>();

    public BaseAdapter(Context mContext) {
        this.mContext = mContext;
        this.mInflater = LayoutInflater.from(mContext);
    }

    /**
     * 初始化调用
     *
     * @param data
     */
    public void setDatas(List<T> data) {
        if (mItems != null && mItems.size() > 0)
            mItems.clear();//清空数据
        this.mItems = data;
        notifyDataSetChanged();
    }

    /**
     * 刷新数据调用
     *
     * @param data
     */
    public void addDatas(List<T> data) {
        mItems.addAll(data);
        notifyDataSetChanged();
    }

    public LayoutInflater getmInflater() {
        return mInflater;
    }

    /**
     * 加载网络图片
     */
    public synchronized RequestManager getImageLoader() {
        if (mImageLoder == null)
            mImageLoder = Glide.with(mContext);
        return mImageLoder;
    }

    /**
     * 显示网络图片
     *
     * @param viewId
     * @param url
     */
    protected void setImageFromNet(ImageView viewId, String url) {
        if (url.startsWith("http") || url.startsWith("https"))
            setImageFromNet(viewId, url, 0);
        else {

            setImageFromNet(viewId, AppConfig.HOST + url, 0);
        }
    }

    /**
     * 加载网络图片可以显示 错误图片
     *
     * @param viewId
     * @param url
     * @param resId
     */
    protected void setImageFromNet(ImageView viewId, String url, int resId) {
        ImageLoader.loadImage(getImageLoader(), viewId, url, resId);
    }


    @Override
    public int getItemCount() {
        return mItems == null ? 0 : mItems.size();
    }

}
